package com.example.service.impl;

import com.example.mapper.ClazzMapper;
import com.example.mapper.StudentMapper;
import com.example.pojo.Clazz;
import com.example.pojo.ClazzQueryParam;
import com.example.pojo.PageResult;
import com.example.pojo.Student;
import com.example.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 条件分页查询班级
     */
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //设置分页参数(PageHelper)
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

        //执行查询、解析结果, 并封装
        Page<Clazz> p = (Page<Clazz>) clazzMapper.list(clazzQueryParam);

        return new PageResult<>(p.getTotal(), p.getResult());
    }

    /**
     * 根据ID删除班级
     */
    @Override
    public void delete(Integer id) throws Exception {
        //查询班级中是否有学员
        List<Student> list = studentMapper.getByClazzId(id);
        if (!list.isEmpty()) {
            throw new Exception("该班级有学员，不能删除");
        }

        clazzMapper.delete(id);
    }

    /**
     * 新增班级
     */
    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    /**
     * 根据ID查询班级
     */
    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    /**
     * 修改班级
     */
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    /**
     * 获取所有班级信息
     */
    @Override
    public List<Clazz> getAllInfo() {
        return clazzMapper.list(new ClazzQueryParam());
    }
}
